package com.qn.meta.service;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.stp.StpUtil;
import com.qn.common.base.BaseServiceImpl;
import com.qn.common.base.model.BasicFetchPage;
import com.qn.common.base.model.RequestPage;
import com.qn.core.exception.QnNullException;
import com.qn.core.exception.UserRegisterException;
import com.qn.core.resources.ResourcesSession;
import com.qn.core.utils.SaltMd5Util;
import com.qn.meta.entity.User;
import com.qn.meta.mapper.UserMapper;
import com.qn.meta.vo.LoginVo;
import com.qn.meta.vo.SessionListVo;
import com.qn.meta.vo.UserLoginVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
 * qingniu-cloud user source analysis
 *
 * @Author: TXG
 * @Date: 2024/6/11
 * @Version V0.0.2
 */
@DubboService(version = "1.0.0")
public class AuthenticationServiceImpl
        extends BaseServiceImpl<User>
        implements AuthenticationService {
    @Autowired
    UserMapper  baseMapper;
    
    @Override
    public UserLoginVo login(LoginVo loginVo) throws QnNullException {
        User where =new User();
        where.setEmail(loginVo.getUsername());
        where.setPhone(loginVo.getUsername());

        User user = baseMapper.getInfo(where);
        if (Objects.isNull(user)) {
            throw new QnNullException("用户不存在或密码错误");
        }
        String md5=SaltMd5Util.md5(loginVo.getPassword());
        if (!SaltMd5Util.verifySaltPassword(md5,user.getPassword())) {
            throw new QnNullException("用户不存在或密码错误");
        }
        UserLoginVo userLogin = new UserLoginVo(user);
        return userLogin;
    }
    @Override
    public void register(User model) throws UserRegisterException {
        User user = baseMapper.getInfo(model);
        if (!Objects.isNull(user)) {
            throw new UserRegisterException(model.getPhone(),model.getEmail(),"用户已存在!");
        }
        String md5=SaltMd5Util.md5(model.getPassword()) ;
        model.setPassword(SaltMd5Util.generateSaltPassword(md5));
        model.setNewUser(model.getName());
        model.setNewTime(new Date());
        model.setUpdataUser(model.getName());
        model.setUpdateTime(new Date());
        model.setStatus(1);
        baseMapper.insert(model);
    }
    
    @Override
    public void logOut() {
        StpUtil.logout();
    }



    @Override
    public void kickout(Integer id) throws QnNullException {
        if (Objects.isNull(id)) {
            throw new QnNullException("用户ID不能为空");
        }
        StpUtil.kickout(id);
    }

    @Override
    public BasicFetchPage<SessionListVo> getSessionList(RequestPage<SessionListVo> rpage) {
        List<SessionListVo> list = new ArrayList<>();
        if (rpage.getPage().equals(1)) {
            rpage.setPage(0);
        }
        List<String> sessionIdList = StpUtil.searchSessionId("", 0, -1, false);
        for (int i = rpage.getPage() * rpage.getPageSize(), len = Math.min(rpage.getPageSize() + i, sessionIdList.size()); i < len; i++) {

            SaSession session = StpUtil.getSessionBySessionId(sessionIdList.get(i));
            List<TokenSign> tokenSignList = session.getTokenSignList();
            SessionListVo model = new SessionListVo();
            model.setId((Integer) session.getLoginId());
            model.setName(session.getString(ResourcesSession.USER_NAME));
            model.setLoginType(session.getLoginType());
            model.setCreateTime(new Date(session.getCreateTime()));
            model.setTimeout(session.getTimeout());
            model.setTokenSignList(tokenSignList);
            model.setClientIp(session.getString(ResourcesSession.CLIENT_IP));
            model.setUserAgent(session.getString(ResourcesSession.USER_AGENT));
            model.setClientLanguage(session.getString(ResourcesSession.CLIENT_LANGUAGE));
            list.add(model);
        }
        return new BasicFetchPage(sessionIdList.size(), list);
    }
}